package com.lvmama.common.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class EncryptionKey {	
	/**
	 * 生成三位随机码
	 * @return
	 */
    public static final String[] s = {"0","1","2","3","4","5","6","7","8","9",
        "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    
    /**
     * 渠道级别的首字符
     */
    public static final String CHANNEL_FIRST_CHARACTER = "1";
    
    /**
     * 设备类型级别的首字符
     */
    public static final String DEVICE_FIRST_CHARACTER = "2";
    
    /**
     * 页面级别的首字符
     */
    public static final String PAGE_FIRST_CHARACTER = "3";
    
    /**
     * code码类型为渠道
     */
    public static final String CODETYPE_CHANNEL = "Channel";
    
    /**
     * code码类型为设备
     */
    public static final String CODETYPE_DEVICE = "Device";
    
    /**
     * code码类型为页面
     */
    public static final String CODETYPE_PAGE = "Page";

	/**
	 * code码类型为坑位
	 */
	public static final String CODETYPE_PIT = "Pit";
    
	/**
	 * 生成随机码
	 * @param digits
	 * @return
	 */
	public String getCode(int digits){
		/*String[] s = {"0","1","2","3","4","5","6","7","8","9",
				"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};*/
		Random ra = new Random();		
		//生成一个随机数
		String code = "";
		for(int i=0;i<digits;i++){
		    code += s[ra.nextInt(s.length)];
		}
		//如果code码和生成的code码相同，递归重新获取
		return code;
	}
	
	/**
	 * 校验随机码是否在数据库中存在，如果存在重新生成
	 * @param codes
	 * @return
	 */
	public String validateCode(List<String> codes, String levelCode, int digits){
	    Map<String,String> map = new HashMap<String,String>();
	    if (codes != null && codes.size() > 0){
	    	for (String code : codes){
	    		map.put(code, code);
	    	}
	    }
        String fiveCode = levelCode + this.getCode(digits);
        boolean contains = map.containsKey(fiveCode);
        while(contains){
            fiveCode = levelCode + this.getCode(digits);
            contains = map.containsKey(fiveCode);
        }
        return fiveCode;
	}


	
}
